package com.framerock.baselib;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import com.framerock.db.DB;

/**
 * 配置文件处理
 * */
public class Config {

    //配置文件路径
    public static String PATH_INI = "",ROOT_PATH = "";

    //配置信息
    private static Map<String, String> configMap = new HashMap<String, String>();

    /**
     *  初始化配置
     * */
    public static Boolean initConfig(String path)
    {
        Properties properties = new Properties();
        String property = System.getProperty("user.dir");
        property    = property.replace("\\", "/");
        ROOT_PATH   = property;
        if(Rock.isEmpt(path)){
            path     = ""+property+"/src/main/resources/config.properties";
        }
        path     = path.replace("\\", "/");
        PATH_INI = path;
        if(!new File(path).exists())return false;
        try {
            InputStream in = new FileInputStream(path);
            if(in != null) {
                properties.load(in);
                Iterator<String> iterator = properties.stringPropertyNames().iterator();
                while (iterator.hasNext()) {
                    String key = iterator.next();
                    String value = properties.getProperty(key);
                    configMap.put(key, value);
                }
                String debug = getConfig("DEBUG");
                AA.DEBUG   = debug.equals("true");
                DB.initConf();
                return true;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 读取配置
     * @param key 主键
     * @param dev 默认值
     * */
    public static String getConfig(String key, String dev)
    {
        String val = configMap.get(key);
        if(Rock.isEmpt(val))val = dev;
        return val;
    }

    /**
     * 读取配置
     * @param key 主键
     * */
    public static String getConfig(String key)
    {
        return getConfig(key, "");
    }

    /**
     * 设置配置
     * @param key 主键
     * @param val 对应值
     * */
    public static void setConfig(String key, String val)
    {
        configMap.put(key, val);
    }
}
